package com.yanyuan.algorithm.search;

import java.util.Scanner;

/**
 * @Description 线性查找
 * @Author yanyuan
 * @Date 14:17 2020/5/6
 * @Version 1.0
 **/
public class LineSearch {

    public static void main(String[] args) {

        int[] arr = {10, 9, 7, 8, 1, 2, 4, 3};
        //定义待输入的元素
        Scanner input = new Scanner(System.in);
        System.out.println("请输入需要找到的数字");
        //定义待查找的元素
        int num = input.nextInt();
        //如果存在返回数组下标
        int result = search(num, arr);
        if(result == -1){
            System.out.println("要查找的数字位于第" + (result+1) + "位");
        }else{
            System.out.println("要查找的数字不存在");
        }

    }

    private static int search(int num, int[] arr) {
        //对数组arr进行遍历
        for (int i = 0; i < arr.length; i ++){
            if(arr[i] == num){
                return i;
            }
        }
        return -1;
    }
}
